// pages/product/detail/detail.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../../api/index'),
    utils = require('../../../utils/util');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        banner: {
            data: [],
            autoplay: true,
            interval: 3000,
            duration: 1000,
            currentSwiper: 0,
            carCount: 0,
            groupList: [],// 正在拼团的商品列表
        },
        price: 3380,
        oprice: 4480,
        isIpx: globalData.isIpx,
        imageBaseUri: globalData.imageBaseUri,
        pageData: {},
        hospitalInfo: {},
        memberType: 1,
        isGroupBuy: false,
        showBuy: false,
        id: '', // 商品id
        attention: '',
        cartCount: 0, // 购物车
        toast: {
            visible: false,
            text: ''
        },
        active: 0,
        status: 0,
        userId: '',
        share: {
            visible: false,
            data: {},
        },
        countDonwTime: {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0
        },
        num: 1,
        groupOrderId: '',
        isAdd: false,
        onum: 1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options, '详情页options')
        let scene = options.scene || '',
            id = options.id || '',
            userId = options.userId || '';

        if (scene) {
            console.log(scene, 'scene')
            // scene 值是什么样的
            // '50024%262008291227289650512'
            if (scene.indexOf('&') != -1) {
                userId = scene.split('&')[0];
                id = scene.split('&')[1];
            } else {
                userId = scene.split('%26')[0];
                id = scene.split('%26')[1];
            }
        }

        this.setData({
            id,
            userId,
            scene
        })
        console.log(this.data.userId, '保存的邀请人id')
        if (this.data.userId) {
            wx.setStorageSync('inviteId', this.data.userId)
        }
        this.reload();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        if (this.data.pageData.isGroup) {
            this.getGroupList()
        }
    },

    onUnload() {
        this.timer && clearInterval(this.timer)
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        let userId = globalData.userInfo.UserId || '';
        console.log(`/pages/product/detail/detail?id=${this.data.id}&userId=${userId}`, '分享链接')
        return {
            title: this.data.pageData.Title,
            path: `/pages/product/detail/detail?id=${this.data.id}&userId=${userId}`,
            imageUrl: this.data.pageData.GoodsFileDtos[0].FilePath
        }
    },

    /**
	 * swiper切换
	 */
    swiperChange(e) {
        this.setData({
            'banner.currentSwiper': e.detail.current
        })
    },

    linkTo(e) {
        let to = e.currentTarget.dataset.to;
        switch (to) {
            case '1':
                wx.reLaunch({
                    url: '/pages/index/index',
                })
                break;
            case '2':
                wx.reLaunch({
                    url: '/pages/car/car',
                })
                break;
            case '3':
                break;
            default:
                return;
        }
    },
    openPop(e) {
        console.log(e.currentTarget.dataset.isadd,'isadd')
        if(e.currentTarget.dataset.isadd==1){
            this.setData({
                isAdd: true,
                onum: 1
            })
        }else {
            this.setData({
                isAdd: false,
                onum: 1
            })
        }
        this.setData({
            showBuy: true,
            showGroup: e.currentTarget.dataset.group == 1 ? true : false,
            groupOrderId: '',
        })
    },
    closePop(e) {
        this.setData({
            showBuy: false,
            num: 1,
            // groupOrderId: ''
        })

    },

    async reload() {
        await this.getGoodsDetail();
        // this.getCartList(); // 获取购物车，以显示购物车个数，不需要了
    },

    // 获取商品详情
    async getGoodsDetail() {
        console.log('avatar', wx.getStorageSync('userinfo').HeadIcon)
        try {
            let res = await api.goods.goodsDetail({ id: this.data.id, invitationId: this.data.userId }),
                data = res.data.ResData || {},
                shareData = this.data.share.data;

            if (data.MarketingTypes.toString().indexOf('2') != -1) {
                data.isSeckill = true
            } else {
                data.isSeckill = false
            }

            if (data.MarketingTypes.toString().indexOf('3') != -1) {
                data.isGroup = true
            } else {
                data.isGroup = false
            }

            shareData = Object.assign(shareData, {
                id: data.Id,
                name: data.Title,
                minPrice: data.isSeckill ? data.SeckillPric : data.Price,
                showMinPrice: data.MarketPrice,
                img: data.GoodsFileDtos ? (data.GoodsFileDtos[0].FilePath || '') : '',
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            // 秒杀倒计时
            if (data.isSeckill) {
                const calcTime = () => {
                    const countDonwTime = utils.countdownTime(data.GoodsSeckillDto.EndTime)
                    this.setData({ countDonwTime })
                }
                if (this.data.countDonwTime.days <= 0) {
                    this.timer = setInterval(calcTime, 1000)
                }
                calcTime()
            }

            this.setData({
                pageData: data,
                "banner.data": data.GoodsFileDtos || [],
                attention: data.Detail,
                status: 2,
                'share.data': shareData,
            })

            console.log(this.data.share.data, '绘制数据')
            this.setImg();
            this.getActive();
            console.log(res, '商品详情', this.data.pageData)
            if (this.data.pageData.isGroup) {
                this.getGroupList()
            }
        } catch (e) {
            console.log(e, '获取商品详情失败')
            this.setData({
                status: 1
            })
        }
    },

    // 富文本显示
    setImg() {
        if (!this.data.attention) {
            return;
        }

        let result = this.data.attention;
        const regex = new RegExp('<p', 'gi');
        const regexDiv = new RegExp('<div', 'gi');
        if (regex.test(this.data.attention)) {
            result = result.replace(regex, `<p style="width:100%;word-break:break-all;margin:0;padding:0;line-height:26px;font-size:14px;color:#6B6E75;"`);

            let result2 = result;
            const regex2 = new RegExp('<img', 'gi');
            if (regex2.test(result)) {
                result2 = result2.replace(regex2, `<img style="width:100%;display:block;margin:0 auto;padding:0;"`);

                let result3 = result2;
                const regex3 = new RegExp('style=""', 'gi');
                if (regex3.test(result2)) {
                    result3 = result3.replace(regex3, `alt`);
                    this.setData({
                        attention: result3
                    })
                } else {
                    this.setData({
                        attention: result2
                    })
                }
            } else {
                this.setData({
                    attention: result
                })
            }
        } else if (regexDiv.test(this.data.attention)) {
            result = result.replace(regexDiv, `<div style="margin:0;padding:0;width:100%;line-height:26px;font-size:14px;color:#6B6E75;"`);

            let result2 = result;
            const regex2 = new RegExp('<img', 'gi');
            if (regex2.test(result)) {
                result2 = result2.replace(regex2, `<img style="width:100%;margin:0;padding:0;"`);

                let result3 = result2;
                const regex3 = new RegExp('style=""', 'gi');
                if (regex3.test(result2)) {
                    result3 = result3.replace(regex3, `alt`);
                    this.setData({
                        attention: result3
                    })
                } else {
                    this.setData({
                        attention: result2
                    })
                }
            } else {
                this.setData({
                    attention: result
                })
            }
        }

        // console.log(this.data.attention, 'attention')
    },

    // 加入购物车
    async addToCar() {
        if (!utils.getLoginState()) {
            return utils.checkLoginState({
                routeUri: 3,
                uri: `/pages/product/detail/detail?id=${this.data.id}&userId=${this.data.userId}`
            });
        }
        let spec = this.data.pageData.GoodsSpecDtos,
            arr = [],
            obj = {
                id: spec[this.data.active].Id,
                userId: wx.getStorageSync('userinfo').UserId || '',
                goodsId: spec[this.data.active].GoodsId,
                num: 1
            }

        // if (wx.getStorageSync('cart')) {
        //     let storageCart = wx.getStorageSync('cart');
        //     arr = storageCart.push(obj);
        //     wx.setStorageSync('cart', arr);
        //     console.log(spec, 'spec', storageCart, arr)
        // } else {
        //     arr = arr.push(obj)
        //     wx.setStorageSync('cart', arr)
        // }

        arr.push(obj)

        try {
            let res = await api.cart.addCart(arr),
                data = res.data.ResData || {};
            console.log(res, '添加购物车');
            this.setData({
                toast: {
                    visible: true,
                    text: '加入购物车成功'
                },
                status: 2
            })
            // this.getCartList();
        } catch (e) {
            console.log(e, '添加购物车失败');
            this.setData({
                toast: {
                    visible: true,
                    text: '加入购物车失败'
                }
            })
        }
    },

    // 获取购物车列表
    async getCartList() {
        let obj = {
            currenetPageIndex: 1,
            pageSize: 100
        }
        try {
            let res = await api.cart.getCartList(obj),
                data = res.data.ResData || {};
            this.setData({
                cartCount: data.Items.length || 0,
                status: 2
            })
            console.log(res, '购物车列表');

        } catch (e) {
            console.log(e, '获取购物侧列表失败')
        }
    },

    // 获取第一个不为0的规格index
    getActive() {
        let specs = this.data.pageData ? this.data.pageData.GoodsSpecDtos : [];
        if (specs) {
            for (let i = 0; i < specs.length; i++) {
                if (specs[i].Stock != 0) {
                    this.setData({
                        active: i
                    });
                    break;
                }
            }
        }
    },

    // 显示分享弹框
    showShare() {
        console.log('111')
        this.setData({ 'share.visible': true });
    },

    // 获取正在拼团的列表
    async getGroupList() {
        console.log(this.data.pageData, 'pagedata')
        try {
            let res = await api.goods.getGroupingList(this.data.pageData.Id),
                data = res.data.ResData || [];
            this.setData({
                groupList: data
            });
            console.log(res, '拼团列表')
        } catch (e) {
            console.log(e, '获取拼团列表失败')
        }
    },
    // 去拼团列表
    toQuickGroup() {
        wx.navigateTo({
            url: `/pages/vipMall/quickGroup/quickGroup?id=${this.data.id}`,
        })
    },

    // 拼团打开购买弹窗
    toGroupDetail(e) {
        console.log(e, 'eeeee')
        this.setData({
            showBuy: true,
            showGroup: e.currentTarget.dataset.group == 1 ? true : false,
            groupOrderId: e.detail.Id || ''
        })
    }

})